package my.learn.tx.onlyAnno.service.impl;

import my.learn.tx.onlyAnno.dao.AccountDao;
import my.learn.tx.onlyAnno.domain.Account;
import my.learn.tx.onlyAnno.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;



@Service
// @Transactional(propagation= Propagation.SUPPORTS, readOnly=true)
public class AccountServiceImpl implements AccountService {

    @Autowired
    AccountDao accountDao;


    @Override
    public Account findById(Integer id) {
        return accountDao.findById(id);
    }

    @Override
    @Transactional
    public Integer updateAccount(Account account) {
        return accountDao.updateAccount(account);
    }

    @Override
    @Transactional
    public String trans(Integer from, Integer to, Float money) {

        if (from > 0 && to > 0 && money > 0) {

            Account fromAccount = accountDao.findById(from);
            Account toAccount = accountDao.findById(to);

            if (fromAccount == null || toAccount == null) return "查询信息有误";
            if (fromAccount.getMoney() < money) return "余额不足";


            fromAccount.setMoney(fromAccount.getMoney() - money);
            toAccount.setMoney(toAccount.getMoney() + money);

            accountDao.updateAccount(fromAccount);
            int a = 2/0;
            accountDao.updateAccount(toAccount);

            return "{200, 'success', '转账成功'}";
        } else {
            return "信息有误";
        }
    }
}
